
from fastapi import FastAPI,Request,applications
from starlette.middleware.cors import CORSMiddleware
from jose import jwt, JWTError
from app.core.config import settings,swagger_monkey_patch
from app.core.exceptions import UnicornException
import time
from fastapi.responses import JSONResponse

applications.get_swagger_ui_html = swagger_monkey_patch
app = FastAPI(title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json")

from app.models.orders.order_model import OrderItem
@app.get("/columns")
def table_columns():
    print(OrderItem.__table__.columns.keys())
    return "ok"
@app.get("palpay/pay/")
def payment(request:Request):
    print(request.body())
    print(request.items())
    return "ok"


# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

async def add_process_time(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=200,
        content={"message":exc.name,"code":403},
    )
'''
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from redis import asyncio as aioredis
@app.on_event("startup")
async def startup():
    redis = aioredis.from_url("redis://localhost", encoding="utf8", decode_responses=True)
    FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
'''

from app.api.api_v1.web_api import api_router
from app.api.api_v1.web_api import no_middle_router
from app.api.api_v1.web_api import user_router
app.include_router(api_router, prefix=settings.API_V1_STR)
app.include_router(no_middle_router, prefix=settings.API_V1_STR)
app.include_router(user_router, prefix=settings.API_V1_STR)
